import cryptoJs from 'crypto-js'

const DEFAULT_KEY = 'tZ9aG2XqdNTS0ENM0YEx6qXE';

/**
 * 加密模式为CBC，补码方式为PKCS5Padding（也就是PKCS7）
 */
const pattern = {
    mode: cryptoJs.mode.ECB,
    padding: cryptoJs.pad.Pkcs7
}

/**
 *  DES(ECB)加密
 * @param {*} data 
 * @param {*} key 
 * @returns 
 */
export const encrypt = function (data, key = null) {
    let encData = cryptoJs.enc.Utf8.parse(data);
    let enctKey = cryptoJs.enc.Utf8.parse(!key ? DEFAULT_KEY : key);

    let encrypted = cryptoJs.TripleDES.encrypt(encData, enctKey, pattern);
    return cryptoJs.enc.Base64.stringify(encrypted.ciphertext);
}

/**
 * 
 * @param {DES(ECB)解密} data 
 * @param {*} key 
 * @returns 
 */
export const decrypt = function (data, key = null) {
    let dataBase64 = cryptoJs.enc.Base64.parse(data);
    let encData = cryptoJs.enc.Base64.stringify(dataBase64);
    let encKey = cryptoJs.enc.Utf8.parse(!key ? DEFAULT_KEY : key);

    let decrypt = cryptoJs.TripleDES.decrypt(encData, encKey, pattern);
    let decryptedStr = decrypt.toString(cryptoJs.enc.Utf8);
    return decryptedStr.toString();
}
